<template>
  <FModal :loading="loading" @ok="toRollbackNode"
          ref="refFModal" width="600" header="退回到指定节点">
    <div>
      <el-text truncated>
        提示: 退回到指定节点后, 审批历史会被保存 ,并且流程将在指定位置重新运转
      </el-text>
    </div>

    <el-select v-model="rollbackNodeId"
               placeholder="请选择需要回退到的节点" clearable filterable>
      <el-option v-for="opt in rollbackAbleNodeList"
                 :key="opt.nodeId" :label="opt.nodeName" :value="opt.nodeId"/>
    </el-select>

    <el-button style="margin-left: 10px" round icon="view"
               @click="previewFlow">查看流程
    </el-button>
  </FModal>

  <FlowModelWithHistory ref="refFlowModelWithHistory"/>
</template>
<script setup>

import FModal from '@/components/FModal/index.vue';
import {shallowRef, unref} from 'vue';
import {getAction} from '@/request/BaseRequest';
import FlowModelWithHistory from '@/components/platwork/FlowModelWithHistory';
import {ElMessage} from 'element-plus';
import {isEmpty} from '@/utils/CommonUtils';

defineProps({
  name: 'ToRollbackNodeComponent'
});
const refFModal = shallowRef();
const refFlowModelWithHistory = shallowRef();
const loading = shallowRef(false);
const rollbackNodeId = shallowRef(undefined);
const rollbackAbleNodeList = shallowRef(undefined);
const emits = defineEmits(['toRollbackNode']);
let userTaskId = undefined;
let userTask = undefined;


function setData(_userTask) {
  userTask = _userTask;
  userTaskId = userTask.id;
  open();
  loadRollbackAbleNode();
}

function loadRollbackAbleNode() {
  loading.value = true;
  getAction('/flow/loadRollbackAbleNode', {userTaskId}).then(data => {
    loading.value = false;
    if (data.success) {
      rollbackAbleNodeList.value = data.result;
    }
  });
}

function previewFlow() {
  refFlowModelWithHistory.value.setData(userTask.processInstanceId);
}

function open() {
  refFModal.value.open();
}

function toRollbackNode() {
  if (isEmpty(rollbackNodeId)) {
    ElMessage({
      message: '请选择需要回退到的节点',
      type: 'warning',
    });
    return;
  }
  loading.value = true;
  emits('toRollbackNode', unref(rollbackNodeId));
}

defineExpose({
  setData
});
</script>
